//创建用户相关的仓库
import { defineStore } from "pinia";
import { reqLogin, reqSign } from "@/api/user/index";

let useUserStore = defineStore("User", {
  //存储数据
  state: () => {
    return {
      token: localStorage.getItem("userToken") || "",
      username: localStorage.getItem("username") || "",
      avatar: localStorage.getItem("avatar") || "",
      id: localStorage.getItem("id") || "",
      role: localStorage.getItem("role") || "",
      mode: "",
    };
  },
  //逻辑
  actions: {
    setState(data) {
      console.log(data);
      this.token = data.token;
      this.username = data.username;
      this.avatar = `data:image/png;base64,${data.avatar}`;
      this.id = data.id;
      this.role = data.role;
      this.mode = data.username === "admin" ? "admin" : "user";
      localStorage.setItem("id", this.id);
      localStorage.setItem("userToken", this.token);
      localStorage.setItem("username", this.username);
      localStorage.setItem("avatar", this.avatar);
      localStorage.setItem("role", this.role);
    },
    async userLogin(data) {
      let res = await reqLogin(data);
      if (res.code == 200) {
        this.setState(res.data);
      }
    },

    async userSignUp(data) {
      let res = await reqSign(data);
      if (res.code == 200) {
        this.setState(res.data);
      }
      console.log(res, data);
    },
    clear() {
      localStorage.clear();
      this.token = "";
      this.username = "";
      this.avatar = "";
      this.id = "";
    },
  },
  getters: {},
});

export default useUserStore;
